/**
 * 
 */
package com.zc.BankCreditManagement.Servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zc.BankCreditManagement.JavaBean.EmailVerify;
import com.zc.BankCreditManagement.ServiceImpl.CustomerServiceImpl;
import com.zc.BankCreditManagement.ServiceImpl.EmailVerifyServiceImpl;
import com.zc.BankCreditManagement.ZCUtil.GetRanNum;
import com.zc.BankCreditManagement.ZCUtil.SendEmail;

/**
 * @author ZhangCheng
 * @time 2019年9月27日
 */
@WebServlet("/EmailServlet")
public class EmailServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8114939817192884386L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String type = req.getParameter("Type");
		if("send".equals(type)) {
			sendEmail(req,resp);
		}else if("verifyCode".equals(type)){
			verifyCode(req,resp);
		}
	}
	private void verifyCode(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int peoId = Integer.parseInt(req.getParameter("peoId"));
		String code = req.getParameter("code");
		EmailVerifyServiceImpl eVSI = new EmailVerifyServiceImpl();
		
		String msg = eVSI.isCodeRight(peoId, code);
		resp.getWriter().write(msg);
	}
	private void sendEmail(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
		int peoId = Integer.parseInt(req.getParameter("peoId"));
		String code = new GetRanNum().RanNum(6);
		
		CustomerServiceImpl cSI = new CustomerServiceImpl();
		String email = cSI.getThisInfoById(peoId, true).getEmail();
		EmailVerify eV = new EmailVerify(peoId, code, null);
		
		EmailVerifyServiceImpl eVSI = new EmailVerifyServiceImpl();
		String responseMsg = eVSI.saveThisCode(eV, 5);
		
		if("成功".equals(responseMsg.split(" ")[1])) {
			SendEmail sE = new SendEmail();
			String msg = "<h1>您的验证码是" + code + "</h1>";
			
			responseMsg = sE.sendEmailContent("wesleycheng@foxmail.com", "", "验证码", msg, email);
		}
		
		resp.setCharacterEncoding("UTF-8");
		System.out.println(responseMsg);
		resp.getWriter().write(responseMsg);
	}
}
